package org.example.backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.example.backend.constant.ResultCode;
import org.example.backend.dto.PageResult;
import org.example.backend.dto.Result;
import org.example.backend.entity.Category;
import org.example.backend.entity.Product;
import org.example.backend.entity.view.StockWarningView;
import org.example.backend.exception.BusinessException;
import org.example.backend.mapper.CategoryMapper;
import org.example.backend.mapper.ProductMapper;
import org.example.backend.mapper.view.StockWarningViewMapper;
import org.example.backend.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 商品控制器
 * 提供商品查询、新增、修改、删除等功能
 */
@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private StockWarningViewMapper stockWarningViewMapper;

    /**
     * 分页查询商品列表
     * @param current 当前页码
     * @param size 每页大小
     * @param name 商品名称（可选，模糊查询）
     * @param categoryId 分类ID（可选，精确查询）
     * @param status 状态（可选，精确查询）
     * @return 分页结果
     */
    @GetMapping("/page")
    public ResponseEntity<Result<PageResult<Product>>> page(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false) Integer status) {

        Page<Product> page = new Page<>(current, size);

        LambdaQueryWrapper<Product> queryWrapper = Wrappers.<Product>lambdaQuery()
                .like(StringUtils.isNotBlank(name), Product::getName, name)
                .eq(categoryId != null, Product::getCategoryId, categoryId)
                .eq(status != null, Product::getStatus, status)
                .orderByDesc(Product::getCreateTime);

        Page<Product> productPage = productMapper.selectPage(page, queryWrapper);

        // 查询分类信息
        productPage.getRecords().forEach(product -> {
            Category category = categoryMapper.selectById(product.getCategoryId());
            if (category != null) {
                product.setDescription(product.getDescription() + " [" + category.getName() + "]");
            }
        });

        return ResponseUtil.success(new PageResult<>(productPage.getTotal(), productPage.getRecords()));
    }

    /**
     * 获取商品详情
     * @param id 商品ID
     * @return 商品详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<Result<Product>> getById(@PathVariable Long id) {
        Product product = productMapper.selectById(id);
        if (product == null) {
            return ResponseUtil.notFound("商品不存在");
        }

        // 查询分类信息
        Category category = categoryMapper.selectById(product.getCategoryId());
        if (category != null) {
            product.setDescription(product.getDescription() + " [" + category.getName() + "]");
        }

        return ResponseUtil.success(product);
    }

    /**
     * 新增商品
     * @param product 商品信息
     * @return 操作结果
     */
    @PostMapping
    public ResponseEntity<Result<Void>> save(@Valid @RequestBody Product product) {
        // 检查分类是否存在
        Category category = categoryMapper.selectById(product.getCategoryId());
        if (category == null) {
            return ResponseUtil.badRequest("分类不存在");
        }

        // 检查商品名称是否已存在
        Long count = productMapper.selectCount(Wrappers.<Product>lambdaQuery().eq(Product::getName, product.getName()));
        if (count > 0) {
            throw new BusinessException(ResultCode.DATA_ALREADY_EXISTED, "商品名称已存在");
        }

        productMapper.insert(product);
        return ResponseUtil.created();
    }

    /**
     * 修改商品
     * @param product 商品信息
     * @return 操作结果
     */
    @PutMapping
    public ResponseEntity<Result<Void>> update(@Valid @RequestBody Product product) {
        if (product.getId() == null) {
            return ResponseUtil.badRequest("ID不能为空");
        }

        Product existProduct = productMapper.selectById(product.getId());
        if (existProduct == null) {
            return ResponseUtil.notFound("商品不存在");
        }

        // 检查分类是否存在
        Category category = categoryMapper.selectById(product.getCategoryId());
        if (category == null) {
            return ResponseUtil.badRequest("分类不存在");
        }

        // 检查商品名称是否已被其他商品使用
        if (!existProduct.getName().equals(product.getName())) {
            Long count = productMapper.selectCount(
                    Wrappers.<Product>lambdaQuery()
                            .eq(Product::getName, product.getName())
                            .ne(Product::getId, product.getId())
            );
            if (count > 0) {
                throw new BusinessException(ResultCode.DATA_ALREADY_EXISTED, "商品名称已存在");
            }
        }

        productMapper.updateById(product);
        return ResponseUtil.success();
    }

    /**
     * 删除商品
     * @param id 商品ID
     * @return 操作结果
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Result<Void>> delete(@PathVariable Long id) {
        Product product = productMapper.selectById(id);
        if (product == null) {
            return ResponseUtil.notFound("商品不存在");
        }

        productMapper.deleteById(id);
        return ResponseUtil.success();
    }

    /**
     * 更新商品状态（上下架）
     * @param id 商品ID
     * @param status 状态值（0-下架，1-上架）
     * @return 操作结果
     */
    @PutMapping("/status")
    public ResponseEntity<Result<Void>> updateStatus(@RequestParam Long id, @RequestParam Integer status) {
        Product product = productMapper.selectById(id);
        if (product == null) {
            return ResponseUtil.notFound("商品不存在");
        }

        Product updateProduct = new Product();
        updateProduct.setId(id);
        updateProduct.setStatus(status);
        productMapper.updateById(updateProduct);

        return ResponseUtil.success();
    }

    /**
     * 更新商品库存
     * @param id 商品ID
     * @param stock 库存数量
     * @return 操作结果
     */
    @PutMapping("/stock")
    public ResponseEntity<Result<Void>> updateStock(@RequestParam Long id, @RequestParam Integer stock) {
        Product product = productMapper.selectById(id);
        if (product == null) {
            return ResponseUtil.notFound("商品不存在");
        }

        if (stock < 0) {
            return ResponseUtil.badRequest("库存不能小于0");
        }

        Product updateProduct = new Product();
        updateProduct.setId(id);
        updateProduct.setStock(stock);
        productMapper.updateById(updateProduct);

        return ResponseUtil.success();
    }

    /**
     * 获取库存预警商品列表
     * @return 库存预警商品列表
     */
    @GetMapping("/stock-warning")
    public ResponseEntity<Result<List<StockWarningView>>> getStockWarning() {
        List<StockWarningView> list = stockWarningViewMapper.selectList(null);
        return ResponseUtil.success(list);
    }

    /**
     * 上传商品图片
     * @param file 图片文件
     * @return 图片路径
     */
    @PostMapping("/upload")
    public ResponseEntity<Result<Map<String, String>>> uploadImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseUtil.badRequest("请选择文件");
        }

        String originalFilename = file.getOriginalFilename();
        System.out.println("上传文件名: " + originalFilename);
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = UUID.randomUUID().toString() + suffix;

        try {
            // 获取绝对路径，确保文件能被保存
            String path = System.getProperty("user.dir");
            String uploadPath = path + "/backend/src/main/resources/static/upload/";
            File uploadDir = new File(uploadPath);
            
            if (!uploadDir.exists()) {
                boolean created = uploadDir.mkdirs();
                System.out.println("创建目录结果: " + created + ", 路径: " + uploadDir.getAbsolutePath());
            }

            // 保存文件
            File dest = new File(uploadDir.getAbsolutePath() + File.separator + filename);
            System.out.println("准备保存文件至: " + dest.getAbsolutePath());
            file.transferTo(dest);
            System.out.println("文件已保存至: " + dest.getAbsolutePath());
            System.out.println("文件是否存在: " + dest.exists() + ", 文件大小: " + dest.length() + " 字节");

            // 返回访问路径
            Map<String, String> result = new HashMap<>();
            result.put("filename", filename);
            result.put("url", "/upload/" + filename);
            
            System.out.println("返回数据: " + result);
            return ResponseUtil.success(result);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseUtil.serverError("文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 检查图片是否存在
     * @param filename 图片文件名
     * @return 操作结果
     */
    @GetMapping("/image-exists")
    public ResponseEntity<Result<Boolean>> checkImageExists(@RequestParam String filename) {
        try {
            // 构建图片路径
            String uploadPath = System.getProperty("user.dir") + "/backend/src/main/resources/static/upload/";
            File imageFile = new File(uploadPath + filename);
            
            // 检查文件是否存在
            boolean exists = imageFile.exists();
            
            return ResponseUtil.success(exists);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.serverError("检查图片失败");
        }
    }
}
